{% extends '_admin.html' %}

{% set DataName='用戶' %}

{% block main_contain %}
<div class="row" id="DataManager">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
              <div class="btn-group">
                <button type="button" class="btn btn-info" data-toggle="modal" data-target="#InsertModal">
                  <i class="fas fa-plus"></i> 新增
                </button>
              </div>
            </div>
            <!-- /.card-header -->
            <div class="card-body">
              <table id="DataView" class="table table-bordered table-hover text-center">
                <thead style="font-size: large;">
                <tr>
                  {% for k, v in ColumnName.items() %}
                  {% if k not in ('id','Password')%}
                  <th>{{ v }}</th>
                  {% endif %}
                  {% endfor %}
                  <th>操作</th>
                </tr>
                </thead>
                <tbody style="font-size: x-large;">
                    {% if TableDatas %}
                    {% for i in TableDatas %}
                    <tr>
                        <td>{{ i.LoginName }}</td>
                        <td>{{ i.UserName }}</td>
                        <td>{{ i.role_name_desc(*ValidRoles) }}</td>
                        <td>{{ i.Phone }}</td>
                        <td>{{ i.CashierName }}</td>
                        <td>
                          <button class="btn btn-sm btn-success" data-toggle="modal" data-target="#ModifyModal" 
                          data-condition="{{ i.id }}">編輯</button>
                          <button class="btn btn-sm btn-danger" data-toggle="modal" data-target="#DeleteModal" 
                          data-condition="{{ i.id }}" data-loginname="{{ i.LoginName }}">刪除</button>
                        </td>
                    </tr>
                    {% endfor %}
                    {% endif %}
                </tbody>
              </table>
            </div>
            <!-- /.card-body -->
          </div>
    </div>

    <!--新增-->
  <div class="modal fade" id="InsertModal" data-backdrop="static" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
      <form id="InsertForm">
        <div class="modal-content">
          <div class="modal-header justify-content-center">
              <h3 class="modal-title">新增{{ DataName }}</h3>
          </div>
          <div class="modal-body">
            <div v-for="(val, key) in InsertData" class="row justify-content-center">
              <div class="input-group mb-3">
                <div class="input-group-prepend">
                  <span class="input-group-text" style="width: 6em;">{[ ColumnName[key] ]}</span>
                </div>
                <select v-if="key=='RoleID'" v-model="InsertData[key]" class="form-control" :name="key">
                  {% for i in ValidRoles %}
                  <option value="{{i['id']}}">{{i['Description']}}</option>
                  {% endfor %}
                </select>
                <select v-else-if="key=='CashierName'" v-model="InsertData[key]" class="form-control" :name="key">
                  {% if ValidCashiers %}
                  {% for i in ValidCashiers %}
                  <option value="{{ i.CashierName }}">{{ i.CashierName }}</option>
                  {% endfor %}
                  {% endif %}
                </select>
                <input v-else v-model="InsertData[key]" class="form-control" :type="key=='Password'?'password':'text'" :name="key">
              </div>
            </div>
          </div>
          <div class="modal-footer justify-content-center">
              <button type="submit" class="btn btn-success">提交</button>
              <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
          </div>
        </div>
        <!-- /.modal-content -->
      </form>
    </div>
  <!-- /.modal-dialog -->
  </div>

  <!--删除-->
  <div class="modal fade" id="DeleteModal">
    <div class="modal-dialog">
        <div class="modal-content">
        <div class="modal-header justify-content-center">
            <h2 class="modal-title text-danger"><i class="fas fa-exclamation-triangle"></i> 請注意</h2>
        </div>
        <div class="modal-body text-center">
            <p class="h5">{[ DeleteData.Message ]}</p>
        </div>
        <div class="modal-footer justify-content-between">
            <button type="button" class="btn btn-success" @click="commit_data('Delete')">確認</button>
            <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
        </div>
        </div>
        <!-- /.modal-content -->
    </div>
  <!-- /.modal-dialog -->
  </div>
  <!--修改-->
  <div class="modal fade" id="ModifyModal" data-backdrop="static" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
      <form id="ModifyForm">
        <div class="modal-content">
          <div class="modal-header justify-content-center">
              <h3 class="modal-title">{{ DataName }}設定</h3>
          </div>
          <div class="modal-body">
            <div v-for="(val, key) in ModifyData" v-if="key!='id'" class="form-group row justify-content-center">
              <label class="col-sm-3 col-form-label text-center">{[ ColumnName[key] ]}：</label>
              <div class="col-sm-8">
                <select v-if="key=='CashierName'" v-model="ModifyData[key]" class="form-control" :name="key">
                  {% if ValidCashiers %}
                  {% for i in ValidCashiers %}
                  <option value="{{ i.CashierName }}">{{ i.CashierName }}</option>
                  {% endfor %}
                  {% endif %}
                </select>
                <input v-else v-model="ModifyData[key]" class="form-control" :type="key=='Password'?'password':'text'" :name="key"
                :readonly="key=='LoginName'?'readonly':false">
              </div>
            </div>
          </div>
          <div class="modal-footer justify-content-center">
              <button type="submit" class="btn btn-success">保存</button>
              <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
          </div>
        </div>
        <!-- /.modal-content -->
      </form>
    </div>
  <!-- /.modal-dialog -->
  </div>
</div>
{% endblock %}


{% block scripts %}
{{ super() }}
<script>
    // 设备管理器
    var DataManager = new Vue({
        el: '#DataManager',
        delimiters: ['{[', ']}'],
        data: {
          InsertData: {
            LoginName: '',
            UserName: '',
            Password: '',
            RoleID: '',
            CashierName: '',
            Phone: '',
          },
          DeleteData:{
            id: '',
            Message: '',
          },
          ModifyData: {
            id: '',
            LoginName: '',
            UserName: '',
            Password: '',
            RoleID: '',
            CashierName: '',
            Phone: '',
          },
          ColumnName: JSON.parse('{{ ColumnNameJSON|safe }}'),
        },
        methods: {
          // 选中当前数据
          seleced_data(condition){
            axios.post("{{ url_for('server.users') }}", {GetData: {id: condition}})
            .then(response => {
              if(response.status==200){
                let ret = response.data
                if(ret.__proto__==Object.prototype){for(key in this.ModifyData){if(ret.hasOwnProperty(key)){this.ModifyData[key]=ret[key]}}}
              }else{AppMessage.fire({icon: 'error', text: '請求錯誤，請聯係管理員'})}
            })
            .catch(function (error) {alert(error)})
          },
          // 提交数据
          commit_data(key){
            let p_data = ''
            // this.insert_carpark_methods(key)
            switch(key){
              case 'Insert': p_data={Insert: this.InsertData};break
              case 'Modify': p_data={Modify: this.ModifyData};break
              case 'Delete': p_data={Delete: this.DeleteData};break
            }
            axios.post("{{ url_for('server.users') }}", p_data)
            .then(response => {
              if(response.status==200){
                  let ret = response.data
                  AppMessage.fire({icon: ret.icon, text: ret.text})
                  if(ret.icon=='success'){
                    if($('#InsertModal').css('display')=="block"){$("#InsertModal").modal('toggle')}
                    if($('#ModifyModal').css('display')=="block"){$("#ModifyModal").modal('toggle')}
                    if($('#DeleteModal').css('display')=="block"){$("#DeleteModal").modal('toggle')}
                    setTimeout("window.location.reload()", 2000);
                  }
              }else{AppMessage.fire({icon: 'error', text: '操作錯誤，請聯係管理員'})}
            })
            .catch(function (error) {alert(error)})
          }
        },
        mounted: function(){
          // 校验新增
          $('#InsertForm').validate({
            rules: {
              LoginName: {required: true},
              UserName: {required: true},
              CashierName: {required: true},
              Password: {min:6},
            },
            errorElement: 'span',
            errorPlacement: function (error, element) {
                error.addClass('invalid-feedback');
                element.closest('.col-sm-8').append(error);
              },
            highlight: function (element, errorClass, validClass) {$(element).addClass('is-invalid')},
            unhighlight: function (element, errorClass, validClass) {$(element).removeClass('is-invalid')},
            submitHandler: function (){DataManager.commit_data('Insert')},
          });
          // 校验编辑
          $('#ModifyForm').validate({
            rules: {
              LoginName: {required: true},
              UserName: {required: true},
              CashierName: {required: true},
              Password: {min:6},
            },
            errorElement: 'span',
            errorPlacement: function (error, element) {
                error.addClass('invalid-feedback');
                element.closest('.col-sm-8').append(error);
              },
            highlight: function (element, errorClass, validClass) {$(element).addClass('is-invalid')},
            unhighlight: function (element, errorClass, validClass) {$(element).removeClass('is-invalid')},
            submitHandler: function (){DataManager.commit_data('Modify')},
          });
          // 数据表
          $('#DataView').DataTable({
              language: {url: "{{ url_for('static', filename='plugins/DataTables/zh_hk.json') }}"},
              responsive: true,
              autoWidth: false,
            });

          // 编辑設備
          $("#ModifyModal").on('show.bs.modal', function (event) {
            let button = $(event.relatedTarget) 
            let condition = button.data('condition')
            DataManager.seleced_data(condition)
          });

          // 删除設備
          $("#DeleteModal").on('show.bs.modal', function (event) {
            let button = $(event.relatedTarget) 
            let condition = button.data('condition')
            let loginname = button.data('loginname')
            DataManager.DeleteData.id = condition
            DataManager.DeleteData.Message = "確認刪除用戶名" + loginname + "的{{ DataName }}嗎？"
          });
        }
    });
</script>
{% endblock %}

